<?php
include 'inc/header.php';

comment('参数传递');
$colors = array('red', 'blue', 'green');
function update($colorArr)
{
    $colorArr[0] = 'pink';
    print_r($colorArr);
}

comment('默认按值传递，不会修改到实参$colors');
update($colors);
newline();
print_r($colors);

comment('按引用传递');
function change(&$colorList)
{
    $colorList[0] = 'purple';
    print_r($colorList);
}

change($colors);
newline();
print_r($colors);


comment('不定参函数');
function mySum()
{
    $count = func_num_args();
    $args = func_get_args();
    $first = func_get_arg(0);
    print_r(array($count, $args, $first));
    $result = 0;
    foreach ($args as $arg) {
        $result += $arg;
    }
    return $result;
}

$result = mySum(1, 10, 7);
clog("my sum result:" . $result);

comment('返回值，按值传递');

function getFavs()
{
    $arr = array('coding', 'reading');
    $GLOBALS['innerFavs'] = $arr;
    return $arr;
}

$outFavs = getFavs();
array_push($outFavs, 'sleeping');
clog("outFavs::" . implode(', ', $outFavs));
newline();
clog("innerFavs::" . implode(', ', $GLOBALS['innerFavs']));
newline();


// 函数名前加 $, 表示函数可以返回引用
function &getMyFavs()
{
    $myArr = array('coding', 'reading');
    // $GLOBALS['innerMyArr'] = $myArr; // 两者并非指向同一数组
    $GLOBALS['innerMyArr'] = &$myArr; // 让两者指向同一数组
    return $myArr;
}

$outMyArr = &getMyFavs();
array_push($outMyArr, 'sleeping');
clog("outMyArr is:" . implode(', ', $outMyArr));
newline();
clog("innerMyArr is:" . implode(', ', $GLOBALS['innerMyArr']));
newline();

comment('匿名函数');
$refFunc = function ($msg) {
    echo $msg;
};
$refFunc('nice to meet you');


comment('闭包使用外部变量');
function getSumFunc()
{
    $num1 = 10;
    $sumFunc = function ($num2) use ($num1) {
        return $num1 + $num2;
    };
    return $sumFunc;
}
$sum = getSumFunc();
clog($sum(20)); //30


function sayHi($msg)
{
    echo "hello ", $msg;
}

comment('ReflectionFunction');
$refFunc = new ReflectionFunction('sayHi');
$refFunc->invoke('alice');

include 'inc/footer.php';